package com.nineclock.auth.processor.impl;

import cn.hutool.core.util.StrUtil;
import com.nineclock.auth.entity.IntegrationAuthenticationEntity;
import com.nineclock.auth.processor.AuthenticationProcessor;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.system.dto.SysUserDTO;
import com.nineclock.system.feign.SysUserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Component
public class UsernameAndPasswordAuthenticationProcessor implements AuthenticationProcessor {


    @Autowired
    SysUserFeign userFeign;

    /**
     * 根据前端传过来的参数，获取 userDTO对象
     * @param entity
     * @return
     */
    @Override
    public SysUserDTO authenticate(IntegrationAuthenticationEntity entity) {
        //获取用户名和密码
        String username = entity.getAuthParameter("username");
        String password = entity.getAuthParameter("password");
        if(StrUtil.isEmpty(username) || StrUtil.isEmpty(password)){
            throw new NcException(ResponseEnum.INVALID_USERNAME_PASSWORD);
        }

        SysUserDTO userDTO = userFeign.queryUser(username).getData();
        if(userDTO == null){
            throw new NcException(ResponseEnum.USER_NOT_FOUND);
        }

        return userDTO;
    }

    /**
     * 判断是否支持 用户名密码认证方式
     * @param entity
     * @return
     */
    @Override
    public boolean support(IntegrationAuthenticationEntity entity) {
        if(entity != null && entity.getAuthType() == null){
            return true;
        }
        return false;
    }
}
